<?php
/**
 * 新建Box Widget
 * User: ZFC
 * Date: 2015/7/8
 * Time: 22:02
 */

namespace common\widgets;

use yii\helpers\Html;

class Box extends Widget {

    public $title;

    /**
     * 菜单按钮组
     * [
     *    [
     *       'text' => '标题',
     *       'href'  => '/admin/add.html',
     *       'icon'  => 'plus',
     *    ]
     * ]
     */
    public $buttons;

    public $headerContent;

    public function init(){
        parent::init();
        echo "<div class='box'>";
        $this->renderHeader();
        echo "<div class='box-body'>";
    }

    public function run(){
        parent::run();
        echo "</div>\n</div>";
    }

    private function renderHeader(){
        if(!empty($this->headerContent)){
            echo '<div class="box-header">'.PHP_EOL;
            echo $this->headerContent;
            echo '</div>';
        }elseif(!empty($this->title)){
            echo '<div class="box-header">'.PHP_EOL.'
                    <h3 class="box-title">'.$this->title.'</h3>';
            echo $this->renderButtons();
            echo '</div>';
        }
    }

    /**
     * 渲染配置中的菜单项
     * @return string
     */
    private function renderButtons(){
        $s = "";
        if(!empty($this->buttons) && is_array($this->buttons)){
            $s .= "<div class='btn-group pull-right'>";
            foreach($this->buttons as $btn){
                $s .= "<a href='".$btn['href']."' class='btn btn-sm btn-primary'>";
                if(!empty($btn['icon']))
                    $s .=  "<i class='glyphicon glyphicon-".$btn['icon']."'></i> ";
                $s .= $btn['text'] . "</a>";
            }
            $s .= "</div>";
        }
        return $s;
    }
}